package imoney.shared;

import java.io.Serializable;

public class UrlUtils implements Serializable {

	private static final long serialVersionUID = 22022013L;

	/**
	 * Create a redirection URL with the source URL stored in an attribute.
	 * @param target : the url to redirect to.
	 * @param source : the url at the source of the redirection.
	 */
	public static String createRedirURL(String target, String source, String gwtCodesvr) {
		String escaped = encode(source);
		String url = target + "?" + Statics.SRC_URL_PARAM + "=" + escaped;
		if (gwtCodesvr.length() > 0) {
			url += "%3Fgwt.codesvr=" + gwtCodesvr;
		}
		return url;
	}
	
	/**
	 * Retrieve the source URL from a redirection URL.
	 * @param redirURL the url containing the source URL as a parameter.
	 * @return
	 */
	public static String getSourceURL(String redirURL) {
		String source = Statics.HOME_URL;
		int index = redirURL.indexOf(Statics.SRC_URL_PARAM+"=");
		if (index >= 0) {
			int startIdx = index + Statics.SRC_URL_PARAM.length() + 1;
			int nextIdx = redirURL.indexOf("&", startIdx);
			int endIdx = nextIdx < 0 ? redirURL.length() : nextIdx;
			source = redirURL.substring(startIdx, endIdx);
		}
		return source; 
	}
	
	/**
	 * Encode the reserved URL chars. To be used before passing an URL as 
	 * another URL parameter. 
	 * @param url the url to encode
	 * @return the new url
	 */
	private static String encode(String url) {
		StringBuilder encoded = new StringBuilder();
		for (int i=0; i<url.length(); i++) {
			char c = url.charAt(i);
			switch (c) {
			case '.':
				encoded.append("%2E");
				break;
			case '?':
				encoded.append("%3F");
				break;
			case '=':
				encoded.append("%3D");
				break;
			case '&':
				encoded.append("%26");
				break;
			default:
				encoded.append(c);
				break;
			}
			
		}
		return encoded.toString();
	}
	
}
